package ULHT.LIG2N1.RC.VO;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WhitelistVO implements Serializable {

    private ArrayList<String> whitelist;
    private final String filename = "WhiteList.Data";

    public String getFilename() {
        return filename;
    }

    public WhitelistVO(ArrayList<String> whitelist) {
        this.whitelist = whitelist;
    }

    public WhitelistVO() {
        try {
            this.whitelist = loadWhiteList();
        } catch (FileNotFoundException ex) {
            this.whitelist = new ArrayList<>();
        } catch (IOException ex) {
            this.whitelist = new ArrayList<>();
        }
    }

    public void addToWhitelist(String ipAddress) {
        this.whitelist.add(ipAddress);
    }

    public void removeFromWhitelist(String ipAddress) {
        if (whitelist.contains(ipAddress)) {
            whitelist.remove(ipAddress);
        }
    }

    public boolean isWhitelisted(String ipAddress) {
        return whitelist.contains(ipAddress);
    }

    public ArrayList<String> getWhitelist() {
        return whitelist;
    }

    public ArrayList<String> loadWhiteList() throws FileNotFoundException, IOException {
        FileManage fileManage = new FileManage();
        return fileManage.readArrayListFromFile(this.filename);
    }

    private void writeWhiteList() throws FileNotFoundException, IOException {
        FileManage fileManage = new FileManage();
        fileManage.writeArrayListToFile(this.whitelist, this.filename);
    }
    
    public void persistWhiteList(){
        try {
            writeWhiteList();
        } catch (FileNotFoundException ex) {
            System.out.println("Erro ao escrever Whitelist");
        } catch (IOException ex) {
            System.out.println("Erro ao escrever Whitelist");
        }
    }
    
    public String getWhiteListStr(){
        String whitelistStr = "";
        Iterator itr = whitelist.iterator();
        while(itr.hasNext()) {
            whitelistStr += itr.next() + "\n";
        }
        if (whitelistStr.equals(""))
            whitelistStr = "Whitelist vazia\n";
        return whitelistStr;
    }
}
